package library.web.servlet.other;

import library.domain.Message;
import library.domain.User;
import library.persistence.dao.MessageDao;
import library.persistence.impl.MessageDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Calendar;

@WebServlet(name = "addMessageServlet",urlPatterns = {"/addMessage"})
public class AddMessageServlet extends HttpServlet {
    private String username;
    private String time;
    private String comment;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.comment = req.getParameter("message");
        System.out.println(comment);
        if(this.comment != null && !this.comment.equals("")) {
            HttpSession session = req.getSession();
            if(session.getAttribute("deleteMsg") != null){
                session.setAttribute("deleteMsg",null);
            }
            User loginAccount = (User) session.getAttribute("loginAccount");
            if(loginAccount != null){
                this.username = loginAccount.getUsername();
            }else{
                this.username = "visitor";
            }
            Calendar cal = Calendar.getInstance();
            int y = cal.get(Calendar.YEAR);
            int m = cal.get(Calendar.MONTH);
            int d = cal.get(Calendar.DATE);
            int h = cal.get(Calendar.HOUR_OF_DAY);
            int mi = cal.get(Calendar.MINUTE);
            int s = cal.get(Calendar.SECOND);
            this.time =  y + "-" + m + "-" + d + " " + h + ":" + mi + ":" + s;

            Message message = new Message(this.username,this.time,this.comment);
            MessageDao messageDao = new MessageDaoImpl();
            messageDao.insertMessage(message);
        }
        resp.sendRedirect("message");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
